import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_taotaoshipin/app/app_controller.dart';
import 'package:flutter_taotaoshipin/http/dao/user_dao.dart';
import 'package:flutter_taotaoshipin/http/dao/userinfo_dao.dart';
import 'package:flutter_taotaoshipin/pages/drama/drama_routes.dart';
import 'package:flutter_taotaoshipin/pages/home/home_routes.dart';
import 'package:flutter_taotaoshipin/pages/login/login_routes.dart';
import 'package:flutter_taotaoshipin/pages/me/me_routes.dart';
import 'package:flutter_taotaoshipin/pages/me/view/contact_dialog.dart';
import 'package:flutter_taotaoshipin/routes/app_routes.dart';
import 'package:flutter_taotaoshipin/util/format_utils.dart';
import 'package:flutter_taotaoshipin/util/image_utils.dart';
import 'package:flutter_taotaoshipin/value/global_config.dart';
import 'package:flutter_taotaoshipin/widget/egg_view.dart';
import 'package:flutter_taotaoshipin/widget/load_image.dart';
import 'package:flutter_taotaoshipin/widget/refresh_header.dart';
import 'package:flutter_taotaoshipin/widget/refresh_status_view.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:visibility_detector/visibility_detector.dart';

import 'me_controller.dart';

class MePage extends StatefulWidget {
  const MePage({Key? key}) : super(key: key);

  @override
  State<MePage> createState() => _MePageState();
}

class _MePageState extends State<MePage> with AutomaticKeepAliveClientMixin {
  final controller = Get.find<MeController>();
  final state = Get.find<MeController>().state;

  @override
  bool get wantKeepAlive => true;

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      body: RefreshStatusView(
        controller: controller,
        contentBuilder: (_) {
          return SmartRefresher(
            controller: controller.refreshController,
            // 下拉刷新
            enablePullDown: true,
            header: const RefreshHeader(),
            onRefresh: controller.onRefresh,
            child: CustomScrollView(
              slivers: [
                _buildUser(),
                _buildItems(),
                _buildHistory(),
                // _buildAd(),
              ],
            ),
          );
        },
      ),
    );
  }

  _buildItems() {
    return SliverToBoxAdapter(
      child: Container(
        margin: EdgeInsets.fromLTRB(17, 10.5, 17, 0),
        padding: EdgeInsets.fromLTRB(0, 25, 0, 17),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(8),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: [
            _buildItem(
              'me/item1',
              '充值记录',
              onTap: () {
                Get.toNamed(MeRoutes.pruchaseRecord);
              },
            ),
            _buildItem(
              'me/item2',
              '投诉反馈',
              onTap: () {
                Get.toNamed(MeRoutes.feedback);
              },
            ),
            _buildItem(
              'me/item3',
              '联系我们',
              onTap: () {
                Get.dialog(
                  ContactDialog(
                    content: GlobalConfig.customerPhone,
                    onSuccess: () {
                      EasyLoading.showToast('复制成功');
                      Clipboard.setData(
                          ClipboardData(text: GlobalConfig.customerPhone!));
                    },
                  ),
                );
              },
            ),
            _buildItem(
              'me/item4',
              '关于我们',
              onTap: () {
                Get.toNamed(MeRoutes.aboutMe);
              },
            ),
          ],
        ),
      ),
    );
  }

  _buildItem(String image, String title, {Function()? onTap}) {
    return GestureDetector(
      onTap: onTap,
      child: Column(
        children: [
          LoadAssetImage(
            image,
            width: 34,
            height: 34,
          ),
          SizedBox(height: 6),
          Text(
            title,
            style: TextStyle(
              color: Color(0xFF333333),
              fontSize: 14,
            ),
          ),
        ],
      ),
    );
  }

  _buildHistory() {
    if (state.historyList.isEmpty) {
      return SliverToBoxAdapter();
    }
    return SliverToBoxAdapter(
      child: Container(
        margin: EdgeInsets.fromLTRB(17, 10.5, 17, 0),
        padding: EdgeInsets.fromLTRB(9, 16, 9, 12),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(8),
        ),
        child: Column(
          children: [
            GestureDetector(
              onTap: () {
                Get.toNamed(HomeRoutes.history);
              },
              child: Row(
                children: [
                  Expanded(
                    child: Text(
                      '播放历史',
                      style: TextStyle(
                        color: Color(0xFF333333),
                        fontSize: 18,
                        fontWeight: FontWeight.w900,
                      ),
                    ),
                  ),
                  LoadAssetImage(
                    'me/arrow_right',
                    width: 11,
                    height: 11,
                  ),
                ],
              ),
            ),
            SizedBox(height: 12),
            SizedBox(
              width: double.infinity,
              height: 172.w,
              child: GridView.builder(
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 1,
                  mainAxisSpacing: 9,
                  crossAxisSpacing: 9,
                  mainAxisExtent: 102.w,
                ),
                scrollDirection: Axis.horizontal,
                itemBuilder: (context, index) {
                  var model = state.historyList[index];
                  return GestureDetector(
                    onTap: () {
                      // 跳转视频详情页
                      Get.toNamed(DramaRoutes.detail, arguments: {
                        'id': model.mainId,
                        'title': model.dramaName,
                        'sort': model.sort,
                      });
                    },
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Stack(
                          children: [
                            AspectRatio(
                              aspectRatio: 102 / 143,
                              child: ClipRRect(
                                borderRadius: BorderRadius.circular(8),
                                child: LoadImage(model.cover ?? ''),
                              ),
                            ),
                            Positioned(
                              left: 0,
                              bottom: 0,
                              right: 0,
                              child: Container(
                                width: double.infinity,
                                alignment: Alignment.centerRight,
                                padding: EdgeInsets.symmetric(
                                    horizontal: 10, vertical: 4),
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.vertical(
                                      bottom: Radius.circular(8)),
                                  gradient: LinearGradient(
                                    colors: [
                                      Colors.transparent,
                                      Color(0x99000000),
                                    ],
                                    begin: Alignment.topCenter,
                                    end: Alignment.bottomCenter,
                                  ),
                                ),
                                child: Text(
                                  '看至${model.sort}集',
                                  style: TextStyle(
                                    color: Colors.white,
                                    fontSize: 10,
                                  ),
                                ),
                              ),
                            ),
                          ],
                        ),
                        SizedBox(height: 12.w),
                        Text(
                          model.dramaName ?? '',
                          style: TextStyle(
                            color: Color(0xFF333333),
                            fontSize: 12,
                            fontWeight: FontWeight.bold,
                          ),
                          maxLines: 1,
                        ),
                      ],
                    ),
                  );
                },
                itemCount: state.historyList.length,
              ),
            ),
          ],
        ),
      ),
    );
  }

  _buildUser() {
    return DecoratedSliver(
      decoration: BoxDecoration(
        image: DecorationImage(
          image: ImageUtils.getAssetImage('me/header'),
          fit: BoxFit.fitWidth,
          alignment: Alignment.topCenter,
        ),
      ),
      sliver: SliverToBoxAdapter(
        child: Column(
          children: [
            SizedBox(height: 83.5.w),
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16),
              child: Row(
                children: [
                  GetBuilder<AppController>(builder: (controller) {
                    return Stack(
                      clipBehavior: Clip.none,
                      children: [
                        EggView(
                          child: LoadAssetImage(
                            'me/avatar',
                            width: 73,
                            height: 73,
                          ),
                          neededNum: 10,
                          onTrigger: (_, __) {
                            Get.toNamed(MeRoutes.debug);
                          },
                        ),
                        if (isVip())
                          Positioned(
                            left: 20,
                            right: 20,
                            bottom: -3,
                            child: LoadAssetImage(
                              'me/vip_tag',
                              width: 30,
                              height: 12,
                            ),
                          ),
                      ],
                    );
                  }),
                  SizedBox(width: 11.5),
                  GetBuilder<AppController>(
                    builder: (controller) {
                      var user = '手机登录';
                      var isGuest =
                          controller.userinfoCenterEntity.mobile!.isEmpty;
                      if (!isGuest) {
                        user = TextUtil.hideNumber(
                            controller.userinfoCenterEntity.mobile!);
                      }
                      return GestureDetector(
                        onTap: () {
                          if (isGuest) {
                            Get.toNamed(LoginRoutes.phoneLogin);
                          }
                        },
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              user,
                              style: TextStyle(
                                color: Colors.white,
                                fontSize: 24,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                            SizedBox(height: 5),
                            Text(
                              'id:${controller.userinfoCenterEntity.id}',
                              style: TextStyle(
                                color: Colors.white,
                                fontSize: 16,
                                fontWeight: FontWeight.normal,
                              ),
                            ),
                          ],
                        ),
                      );
                    },
                  ),
                ],
              ),
            ),
            Stack(
              children: [
                Positioned(
                  left: 0,
                  right: 0,
                  top: 70.5.w,
                  bottom: 0,
                  child: Container(
                    decoration: BoxDecoration(
                      color: Color(0xFFEBEFF7),
                      borderRadius:
                          BorderRadius.vertical(top: Radius.circular(20)),
                    ),
                  ),
                ),
                GetBuilder<AppController>(builder: (_) {
                  String viptime = DateUtil.formatDateMs(
                      (_.userinfoCenterEntity.plusExpire ?? 0) * 1000,
                      format: 'yyyy.MM.dd');
                  int coin = _.userinfoCenterEntity.money! +
                      _.userinfoCenterEntity.giveMoney!;
                  return Padding(
                    padding: EdgeInsets.fromLTRB(16, 18, 16, 0),
                    child: Container(
                      height: 128.w,
                      decoration: BoxDecoration(
                        image: DecorationImage(
                          image: ImageUtils.getAssetImage('me/vip_bar_bg'),
                          fit: BoxFit.fitWidth,
                          alignment: Alignment.topCenter,
                        ),
                      ),
                      child: Padding(
                        padding: EdgeInsets.fromLTRB(18, 26.5.w, 0, 16),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Row(
                              children: [
                                LoadAssetImage(
                                  'me/vip',
                                  width: 16,
                                  height: 16,
                                ),
                                SizedBox(width: 5.5),
                                Text(
                                  isVip() ? '$viptime到期' : '开通会员',
                                  style: TextStyle(
                                    color: Colors.white,
                                    fontSize: 16,
                                    fontWeight: isVip()
                                        ? FontWeight.normal
                                        : FontWeight.bold,
                                  ),
                                ),
                              ],
                            ),
                            SizedBox(height: 10.w),
                            if (isVip())
                              Row(
                                children: [
                                  LoadAssetImage(
                                    'me/coin',
                                    width: 16,
                                  ),
                                  SizedBox(width: 6),
                                  Text(
                                    '金币：$coin',
                                    style: TextStyle(
                                      color: Colors.white,
                                      fontSize: 16,
                                    ),
                                  ),
                                ],
                              )
                            else
                              Text(
                                '会员畅享全网热门短剧',
                                style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 14,
                                ),
                              ),
                            SizedBox(height: 10.w),
                            GestureDetector(
                              onTap: () {
                                Get.toNamed(AppRoutes.subscription);
                              },
                              child: Container(
                                padding: EdgeInsets.symmetric(
                                    horizontal: 14, vertical: 5),
                                decoration: BoxDecoration(
                                  color: Colors.white,
                                  borderRadius: BorderRadius.circular(8),
                                ),
                                child: Text(
                                  isVip() ? '立即查看' : '立即开通',
                                  style: TextStyle(
                                    color: Color(0xFF012078),
                                    fontSize: 14,
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  );
                }),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
